package com.yeyks.controller.other;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.yeyks.account.dal.dao.AccountInfoMapper;
import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.account.dto.AccountDTO;
import com.yeyks.account.param.AccountInfoQueryParam;
import com.yeyks.account.param.LoginParam;
import com.yeyks.account.service.SysDeptService;
import com.yeyks.account.utils.AccountUtil;
import com.yeyks.annotation.*;
import com.yeyks.base.BaseController;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.base.PageInfo;
import com.yeyks.common.constants.AccountType;
import com.yeyks.common.constants.SysLogMsg;
import com.yeyks.common.em.ResponseStatus;
import com.yeyks.common.exception.PermissionInvalidException;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.exception.TokenInvalidException;
import com.yeyks.common.utils.*;
import com.yeyks.common.utils.webutil.Arguments;
import com.yeyks.commonReference.append.redis.RedisManager;
import com.yeyks.commonReference.append.sms.SmsService;
import com.yeyks.commonReference.pojo.dto.AddSysUserDTO;
import com.yeyks.commonReference.pojo.param.AddBusinessParam;
import com.yeyks.commonReference.pojo.param.QueryBusinessParam;
import com.yeyks.commonReference.service.account.AccountInfoService;
import com.yeyks.commonReference.service.message.MessageService;
import com.yeyks.config.dal.dao.LoginHistoryMapper;
import com.yeyks.config.dal.domain.LoginHistory;
import com.yeyks.consumer.dal.dao.UserInfoMapper;
import com.yeyks.hotel.dal.dao.HotelInfoMapper;
import com.yeyks.hotel.dal.domain.HotelInfo;
import com.yeyks.web.AccountUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账户管理接口
 *
 * @author Beacon
 * @version $Id: AccountController.java, v 0.1 2018年07月30日 17:18 Beacon Exp $
 */
@Api(tags = "账户模块")
@Slf4j
@RestController
@RequestMapping(value = "/ajax/account")
public class AccountController extends BaseController {

    @Autowired
    AccountInfoService accountService;

    @Autowired
    AccountInfoMapper accountInfoMapper;

    @Autowired
    LoginHistoryMapper loginHistoryMapper;

    @Autowired
    HotelInfoMapper hotelInfoMapper;

    @Autowired
    SmsService smsService;

    @Autowired
    MessageService messageService;

    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    RedisManager redisManager;
    @Autowired
    SysDeptService sysDeptService;


    protected boolean checkRegParam(AddSysUserDTO param, AjaxResponseBody responseBody) {

        if ((param.getPhone() == null || param.getPhone().isEmpty()) &&
                (param.getUsername() == null || param.getUsername().isEmpty())) {
            responseBody.setCode(ResponseStatus.RS_ACCOUNT_REG_INVALIDNAME.getCode());
            responseBody.setMsg(ResponseStatus.RS_ACCOUNT_REG_INVALIDNAME.getMsg());
        }

        if (Arguments.notEmpty(param.getPhone()) && TextValidator.MOBILE.boolCheck(param.getPhone())) {
            // 2.输入的手机格式不对时，系统给出提示【手机格式不正确】。
            responseBody.setCode(ResponseStatus.RS_ACCOUNT_REG_INVALIDPHONE.getCode());
            responseBody.setMsg(ResponseStatus.RS_ACCOUNT_REG_INVALIDPHONE.getMsg());
        } else if (param.getPassword() == null ||
                param.getPassword().length() < 6 ||
                param.getPassword().length() > 16) {
            // 3.输入的密码过长或过短时，系统给出提示【密码的有效长度为6-16位】。
            responseBody.setCode(ResponseStatus.RS_ACCOUNT_REG_INVALIDPWD.getCode());
            responseBody.setMsg(ResponseStatus.RS_ACCOUNT_REG_INVALIDPWD.getMsg());
            return false;
        } else if (Arguments.notEmpty(param.getUsername()) &&
                param.getUsername().length() > 32) {
            // 4.输入的登陆用户名不对
            responseBody.setCode(ResponseStatus.RS_ACCOUNT_REG_INVALIDUSERNAME.getCode());
            responseBody.setMsg(ResponseStatus.RS_ACCOUNT_REG_INVALIDUSERNAME.getMsg());
            return false;
        }

        return true;
    }

    /**
     * 注册账号接口
     *
     * @param addSysUserDTO 创建账号参数
     * @return
     */
    @Login
    @ApiOperation(value = "添加账号", notes = "添加账号，只有部门经理才可以加添加本部门下账号")
    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    public Result reg(@ApiIgnore @LoginUser AccountInfo loginUser, AddSysUserDTO addSysUserDTO) {
        AjaxResponseBody response = new AjaxResponseBody();

        if (checkRegParam(addSysUserDTO, response)) {
            List<AccountInfo> existAccount = accountInfoMapper.selectByPhoneOrUsername(null, addSysUserDTO.getUsername());
            if (existAccount != null && existAccount.size() > 0) {
                return Result.error("账号:" + addSysUserDTO.getUsername() + "已存在");
            }
        } else {
            return Result.error(response.getCode(), response.getMsg());
        }
        accountService.saveUser(loginUser, addSysUserDTO);

        return Result.ok("操作成功");
    }


    @Login
    @RequestMapping(value = "/list/queryDeveloper", method = RequestMethod.POST)
    @ApiOperation(value = "获取【运营商】账户列表", notes = "获取【运营商】账户列表接口", response = AccountInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "name", value = " ", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "accountType", value = " ", dataType = "Integer", required = true)
    })
    public AjaxResponseBody<List<AccountInfo>> queryDeveloper(String name,Integer accountType) {
        List<AccountInfo> accountInfoList = accountService.queryDeveloper(name, accountType);
        return AjaxResponseBody.success(accountInfoList);
    }

    @Login
    @RequestMapping(value = "/list/queryAgent", method = RequestMethod.POST)
    @ApiOperation(value = "获取代理商账户列表", notes = "获取【省代/市代】账户列表接口", response = AccountInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "name", value = " ", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "accountType", value = " ", dataType = "Integer", required = true)
    })
    public AjaxResponseBody<List<AccountInfo>> queryAgent(String name,Integer accountType) {
        List<AccountInfo> accountInfoList = accountService.queryAgent(name, accountType);
        return AjaxResponseBody.success(accountInfoList);
    }

    @Login
    @ApiOperation(value = "添加【运营商/卡商】账户接口（V3.8.1.UPDATE）", notes = "添加【运营商/卡商】不同页面输入不同的Type（V3.8.1.UPDATE）")
    @RequestMapping(value = "/add/business", method = RequestMethod.POST)
    public Result addBusiness(@LoginUser AddBusinessParam param) {

        AjaxResponseBody response = new AjaxResponseBody();
        AccountInfo loginUser = AccountUtils.getLoginUser();
        if (null != param) {
            if (checkRegParam(ObjectConvertUtil.convertObject(param, AddSysUserDTO.class), response)) {
                List<AccountInfo> existAccount = accountInfoMapper.selectByPhoneOrUsername(null, param.getUsername());
                if (existAccount != null && existAccount.size() > 0) {
                    return Result.error("账号:" + param.getUsername() + "已存在");
                }
            } else {
                return Result.error(response.getCode(), response.getMsg());
            }
        }

        //执行添加
        accountService.saveBusiness(loginUser, param);
        return Result.ok("操作成功");
    }

    @Login
    @RequestMapping(value = "/list/business", method = RequestMethod.POST)
    @ApiOperation(value = "获取【运营商/卡商】账户列表（V3.8.1.UPDATE）", notes = "获取【运营商/服务商/卡商】账户列表接口（V3.8.1.UPDATE）", response = AccountInfo.class)
    public Result listBusiness(@Valid QueryBusinessParam param) {

        AccountInfo loginUser = AccountUtils.getLoginUser();
        if (null == loginUser) {
            throw new ServiceException("账号token过期，重新登录");
        }
        Map<String, Object> map = Maps.newHashMap();
        //执行分页查询
        List<AccountInfo> accountInfoList = accountService.listBusiness(param, loginUser);
        int count = accountService.countBusiness(param, loginUser);
        map.put("lists", accountInfoList);
        map.put("count", count);
        return Result.ok().put("body", map);
    }

    @Login
    @RequestMapping(value = "/get/saler/list", method = RequestMethod.POST)
    @ApiOperation(value = "获取售卡商账户列表（V3.8.1.UPDATE）", notes = "V3.8.1获取【运营商/卡商】账户列表接口（V3.8.1.UPDATE）", response = AccountInfo.class)
    public Result getSalerList(@RequestParam(value = "name", required = false) String name,
                               @RequestParam(value = "hotelId", required = false) Integer hotelId) {

        AccountInfo loginUser = AccountUtils.getLoginUser();
        if (null == loginUser) {
            throw new ServiceException("账号token过期，重新登录");
        }
        //【尊享】
        Integer vipType = 1;
        List<AccountInfo> accountInfoList = accountService.getSalerList(name, hotelId, vipType);

        return Result.ok().put("body", accountInfoList);
    }

    @NeedToken
    @RequestMapping(value = "/get/min/saler/list", method = RequestMethod.POST)
    @ApiOperation(value = "更新获取【优享】售卡商账户列表（V3.8.1.UPDATE）", notes = "更新获取【优享】售卡商账户列表接口（V3.8.1.UPDATE）", response = AccountInfo.class)
    public Result getMinSalerList(@RequestParam(value = "name", required = false) String name,
                               @RequestParam(value = "hotelId", required = false) Integer hotelId) {

        AccountInfo loginUser = AccountUtils.getLoginUser();
        if (null == loginUser) {
            throw new ServiceException("账号token过期，重新登录");
        }
        //【优享】(已取消服务商的查询)
        Integer vipType = 2;
        List<AccountInfo> accountInfoList = accountService.getSalerList(name, hotelId, vipType);

        return Result.ok().put("body", accountInfoList);
    }


    /**
     * 用户登录
     *
     * @param loginParam
     * @return
     */
    // @ApiIgnore
    @NoLogin
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(
            @RequestBody LoginParam loginParam, HttpServletRequest request) {
        log.info("参数{}", loginParam);
        AccountInfo accountInfo = null;
        if (Arguments.notEmpty(loginParam.getUsername())) {
            QueryWrapper<AccountInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(AccountInfo::getUsername, loginParam.getUsername())
                    .eq(AccountInfo::getPassword, loginParam.getPassword());

            accountInfo = accountService.getOne(queryWrapper);
        }
        if (accountInfo != null) {
            if (!accountInfo.getValid()) {
                throw new ServiceException("账号已被停用");
            }
            if("1".equals(loginParam.getType()))//运营后台账户
            {
                if(AccountType.MinOperateMerchant==accountInfo.getType()|| AccountType.MinVipCardMerchant==accountInfo.getType()||AccountType.MinServiceMerchant==accountInfo.getType())
                {
                    throw new ServiceException("运营商账号无权登录");
                }
            }

            if("2".equals(loginParam.getType()))//运营商后台账户
            {
                if(AccountType.Administrator==accountInfo.getType()|| AccountType.ProvinceManager==accountInfo.getType()||AccountType.CityAgent==accountInfo.getType()||AccountType.CityManager==accountInfo.getType()||AccountType.HotelManager==accountInfo.getType())
                {
                    throw new ServiceException("账号无权登录");
                }
            }

            String token = JWTUtil.createToken(String.valueOf(accountInfo.getId()));
            Map<String, Object> map = new HashMap<>();
            List<Long> roleIdList = accountService.selectRoleIdList(accountInfo.getId());
            accountInfo.setRoleIdList(roleIdList);
            map.put("user_info", accountInfo);
            map.put("token", token);
            map.put("roleIdList", Joiners.COMMA.join(accountInfo.getRoleIdList()));
            if(AccountType.HotelManager==accountInfo.getType()){
                HotelInfo hotel = hotelInfoMapper.selectByHotelManager(accountInfo.getId()) ;
                if(null!=hotel)
                {
                    map.put("vipFlag", hotel.getVipFlag());
                }else {
                    map.put("vipFlag", "");
                }
            }
            LoginHistory loginHistory = new LoginHistory();
            loginHistory.setUserId(Integer.valueOf(String.valueOf(accountInfo.getId())));
            loginHistory.setUsername(accountInfo.getUsername());
            loginHistory.setRes("success");
            loginHistory.setType("web");
            loginHistory.setIp(getIpAddr(request));
            loginHistoryMapper.insert(loginHistory);
            return Result.ok().put("body", map);
        } else {
            if (Arguments.notEmpty(loginParam.getUsername()) && Arguments.notEmpty(loginParam.getPassword())) {
                LoginHistory loginHistory = new LoginHistory();
                loginHistory.setUsername(loginParam.getUsername());
                loginHistory.setRes("fail");
                loginHistory.setType("web");
                loginHistoryMapper.insert(loginHistory);
            }
            return Result.error(ResponseStatus.RS_ACCOUNT_NAME_PASSWORD_WRONG.getCode(), ResponseStatus.RS_ACCOUNT_NAME_PASSWORD_WRONG.getMsg());
        }
    }


    /**
     * 获得账户的完整信息
     *
     * @return
     */
    @NeedToken
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    @ApiOperation(value = "获得账户的完整信息", notes = "获得账户的完整信息", response = AccountInfo.class)
    public ResponseEntity<?> getInfo(
            HttpServletRequest request, HttpServletResponse response,
            AccountInfo param
    ) {
        AjaxResponseBody responseBody = new AjaxResponseBody();
        try {
            AccountInfo operatorInfo = AccountUtils.getLoginUser();

            AccountInfo accountInfo = null;
            if (param.getId() != null && param.getId() != 0) {
                accountInfo = accountInfoMapper.selectByPrimaryKey(param.getId());
                if (operatorInfo.getType() >= accountInfo.getType()) {
                    throw new PermissionInvalidException();
                }
            } else {
                accountInfo = AccountUtils.getLoginUser();
            }

            responseBody.setBody(accountInfo);
            responseBody.setCode(ResponseStatus.RS_SUCCESS.getCode());
            responseBody.setMsg(ResponseStatus.RS_SUCCESS.getMsg());
        } catch (PermissionInvalidException e) {
            responseBody.setCode(ResponseStatus.RS_FAIL_INVALID_PERMISSION.getCode());
            responseBody.setMsg(ResponseStatus.RS_FAIL_INVALID_PERMISSION.getMsg());
        } catch (Throwable e) {
            responseBody.setCode(ResponseStatus.RS_FAIL.getCode());
            responseBody.setMsg(e.getMessage());
        }

        return ResponseEntity.ok(responseBody);
    }

    @NeedToken
    @SystemLog(value = SysLogMsg.ACCOUNT_UPDATE_MSG)
    @RequestMapping(value = "/setInfo", method = RequestMethod.POST)
    public ResponseEntity<?> setInfo(@RequestParam(name = "force", defaultValue = "false", required = true) Boolean force, AccountInfo param) {
        AjaxResponseBody responseBody = new AjaxResponseBody();
        try {
            if (StrUtil.isNotBlank(param.getUsername())) {
                param.setUsername(null);
            }
            AccountInfo operatorInfo = AccountUtils.getLoginUser();
            if (param.getId() == null || param.getId() == 0) {
                // 操作自己本身账户
                param.setId(operatorInfo.getId());
            }

            AccountInfo accountInfo = accountInfoMapper.selectByPrimaryKey(param.getId());
            if (accountInfo == null) {
                throw new Exception("account not exist");
            } else if (operatorInfo.getType() > accountInfo.getType()) {
                throw new PermissionInvalidException();
            } else if (operatorInfo.getType().equals(accountInfo.getType())) {
                if (operatorInfo.getId().intValue() != accountInfo.getId().intValue()) {
                    throw new PermissionInvalidException();
                }
            }

            if (param.getUsername() != null) {
                AccountInfo acc = accountInfoMapper.selectByUsername(param.getUsername());
                if (acc != null && !(acc.getId().equals(accountInfo.getId()))) {
                    responseBody.setCode(ResponseStatus.RS_FAIL.getCode());
                    responseBody.setMsg("账号已经存在");
                    return ResponseEntity.ok(responseBody);
                }
            }


            // 某些信息无法修改
            param.setType(accountInfo.getType());
            param.setParentId(accountInfo.getParentId());
            if (param.getPhone() != null && !param.getPhone().equals(accountInfo.getPhone())) {
                List<AccountInfo> accountInfos = accountInfoMapper.selectByPhoneOrUsername(param.getPhone(), null);

                if (!accountInfos.isEmpty()) {
                    responseBody.setCode(ResponseStatus.RS_ACCOUNT_EXIST_PHONE.getCode());
                    responseBody.setMsg(ResponseStatus.RS_ACCOUNT_EXIST_PHONE.getMsg());

                    return ResponseEntity.ok(responseBody);
                }
            }
            param.setPassword(accountInfo.getPassword());
            if (operatorInfo.getType() != AccountType.Administrator &&
                    operatorInfo.getType() != AccountType.ProvinceManager) {
                param.setUsername(accountInfo.getUsername());
            }
            if (operatorInfo.getType().equals(AccountType.Administrator) && param.getArea() != null) {
                accountInfo.setArea(param.getArea());
            }
            if (param.getValid() != null) {
                accountInfo.setValid(param.getValid());
            }


            // 填充原始字段
//            if (!force) {
//                BeanUtils.copyProperties(accountInfo, param);
//            }


            int result = accountService.updateNotNullField(param);
            if (result == 0) {
                throw new Exception("dal exception");
            }

            responseBody.setBody(result);
            responseBody.setCode(ResponseStatus.RS_SUCCESS.getCode());
            responseBody.setMsg(ResponseStatus.RS_SUCCESS.getMsg());
        } catch (TokenInvalidException e) {
            responseBody.setCode(ResponseStatus.RS_FAIL_INVALID_TOKEN.getCode());
            responseBody.setMsg(ResponseStatus.RS_FAIL_INVALID_TOKEN.getMsg());
        } catch (Throwable e) {
            responseBody.setCode(ResponseStatus.RS_FAIL.getCode());
            responseBody.setMsg(ResponseStatus.RS_FAIL.getMsg());
        }

        return ResponseEntity.ok(responseBody);
    }

    @NeedToken
    @SystemLog(value = SysLogMsg.ACCOUNT_UPDATE_PWD)
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
    public ResponseEntity<?> modifyPassword(@RequestParam(name = "origPwd", defaultValue = "", required = true) String origPwd,
                                            AccountInfo param) {
        AjaxResponseBody responseBody = new AjaxResponseBody();
        try {
            if (param.getPassword() == null || param.getPassword().isEmpty()) {
                throw new Exception("The contents of the password cannot be empty");
            }

            AccountInfo operatorInfo = AccountUtils.getLoginUser();
            AccountInfo origAccountInfo;
            if (param.getId() == null || param.getId() == 0 || param.getId().equals(operatorInfo.getId())) {
                param.setId(operatorInfo.getId());
                origAccountInfo = accountInfoMapper.selectByPrimaryKey(param.getId());
            } else {
                origAccountInfo = accountInfoMapper.selectByPrimaryKey(param.getId());
                if (origAccountInfo.getType() <= operatorInfo.getType()) {
                    throw new PermissionInvalidException();
                }
            }

            if (!origPwd.isEmpty() && !origPwd.equals(origAccountInfo.getPassword())) {
                responseBody.setCode(ResponseStatus.RS_ACCOUNT_ORIG_PASSWORD_WRONG.getCode());
                responseBody.setMsg(ResponseStatus.RS_ACCOUNT_ORIG_PASSWORD_WRONG.getMsg());
                return ResponseEntity.ok(responseBody);
            }

            int rec = accountInfoMapper.modifyPasswordById(param.getId(), param.getPassword());

            if (rec != 0) {
                redisManager.delete("account:token:" + origAccountInfo.getId());
                responseBody.setBody(param);
            } else {
                throw new Exception("Updated 0 item");
            }

            responseBody.setCode(ResponseStatus.RS_SUCCESS.getCode());
            responseBody.setMsg(ResponseStatus.RS_SUCCESS.getMsg());
        } catch (TokenInvalidException e) {
            responseBody.setCode(ResponseStatus.RS_FAIL_INVALID_TOKEN.getCode());
            responseBody.setMsg(ResponseStatus.RS_FAIL_INVALID_TOKEN.getMsg());
        } catch (Throwable e) {
            responseBody.setCode(ResponseStatus.RS_FAIL.getCode());
            responseBody.setMsg(e.getMessage());
        }

        return ResponseEntity.ok(responseBody);
    }

    /**
     * 上级修改密码
     *
     * @param newPwd
     * @param id
     * @return
     */
    @NeedToken
    @SystemLog(value = SysLogMsg.ACCOUNT_PARENT_UPDATE_PWD)
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public ResponseEntity<?> updatePassword(
            @RequestParam(name = "newPwd") String newPwd,
            @RequestParam(name = "id") Integer id) {
        if (Arguments.isEmpty(newPwd) || Arguments.isNullOrZero(id)) {
            throw new ServiceException("参数传递有误");
        }
        AccountInfo operatorInfo = AccountUtils.getLoginUser();
        AccountInfo origAccountInfo = accountInfoMapper.selectByPrimaryKey(id);
        if (operatorInfo.getType() != null
                && origAccountInfo.getType() != null
                && operatorInfo.getType() > origAccountInfo.getType()) {
            throw new ServiceException("您无权修改密码");
        }
        int rec = accountInfoMapper.modifyPasswordById(id, newPwd);

        if (rec == 0) {
            throw new ServiceException("修改数据失败");
        }
        redisManager.delete("account:token:" + id);
        return ResponseEntity.ok(AjaxResponseBody.success());
    }


    /**
     * 根据条件查询当前用户下账号的个数
     *
     * @param request
     * @param response
     * @param token
     * @param child
     * @param dtStart
     * @param dtEnd
     * @return
     */
    @RequestMapping(value = {"/count"}, method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseEntity<?> count(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(name = "token", defaultValue = "", required = true) String token,
            @RequestParam(name = "child", defaultValue = "false", required = true) Boolean child, // 是否只搜索
            @RequestParam(name = "dtStart", defaultValue = "0", required = true) Long dtStart,
            @RequestParam(name = "dtEnd", defaultValue = "0", required = true) Long dtEnd
    ) {
        AjaxResponseBody responseBody = new AjaxResponseBody();
        try {

            AccountInfo operatorInfo = accountService.token2AccountInfo(token);
            String start = null;
            if (dtStart != null) {
                start = DateUtils.stampToYMDHMS(String.valueOf(dtStart));
            }
            String end = null;
            if (dtEnd != null) {
                end = DateUtils.stampToYMDHMS(String.valueOf(dtEnd));
            }

            int count = accountInfoMapper.countOfChildren((child ? operatorInfo.getId() : null),
                    start == null ? null : DateUtils.toDateTime(start),
                    end == null ? null : DateUtils.toDateTime(end));

            responseBody.setBody(count);
            responseBody.setCode(ResponseStatus.RS_SUCCESS.getCode());
            responseBody.setMsg(ResponseStatus.RS_SUCCESS.getMsg());
        } catch (Throwable e) {
            responseBody.setCode(ResponseStatus.RS_FAIL.getCode());
            responseBody.setMsg(ResponseStatus.RS_FAIL.getMsg());
        }

        return ResponseEntity.ok(responseBody);
    }


    @ApiOperation(value = "分页查询列表", notes = "根据参数查询省级代理、市级别代理、城市运营商")
    @PostMapping(value = {"/query/list"})
    public ResponseEntity<?> queryList(AccountInfoQueryParam accountInfoQueryParam,
                                       @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        if (accountInfoQueryParam == null) {
            throw new ServiceException("查询参数为空");
        }
        AccountInfo operatorInfo = accountService.token2AccountInfo(accountInfoQueryParam.getToken());

        //count和list
        PageInfo pageInfo = PageInfo.of(pageNum, pageSize);
        accountInfoQueryParam.setOperatorId(AccountUtil.getOperationUserId(operatorInfo));
        accountInfoQueryParam.setOperatorType(operatorInfo.getType());
        accountInfoQueryParam.setOffset(pageInfo.getOffset());
        accountInfoQueryParam.setLimit(pageInfo.getLimit());

        Map<String, Object> map = new HashMap<String, Object>();

        //分页查询 1 总公司 2 查省代列表  3 查市代列表 4 查区县运营中心列表
        List<AccountInfo> accountInfos = accountService.queryPageList(accountInfoQueryParam);
        int count = accountService.queryListCount(accountInfoQueryParam);
        List<AccountDTO> accountDTOS = new ArrayList<>();
        if (accountInfos != null && accountInfos.size() > 0) {
            // List<AccountInfo> accountInfos = (List<AccountInfo>) map.get("list");
            for (AccountInfo info : accountInfos) {
                AccountDTO accountDTO = ObjectConvertUtil.convertObject(info, AccountDTO.class);
                //查询各账号下签约酒店的数量
                if (accountInfoQueryParam.getType() == 2) {   //省代
                    int countChildren = accountInfoMapper.countOfGrandchildchildren(info.getId(), null, null);
                    accountDTO.setGrandchildrenCount(countChildren);
                } else if (accountInfoQueryParam.getType() == 3) { //市代
                    int countGrandchildren = accountInfoMapper.countOfGrandchildren(info.getId(), null, null);
                    accountDTO.setGrandchildrenCount(countGrandchildren);
                } else if (accountInfoQueryParam.getType() == 4) { //区县
                    int countGrandchildren = accountInfoMapper.countOfHotelByCounty(info.getId(), null, null);
                    accountDTO.setGrandchildrenCount(countGrandchildren);
                } else {
                    throw new ServiceException("当前用户权限不足");
                }
                accountDTOS.add(accountDTO);
            }
        }
        map.put("list", accountDTOS);
        map.put("count", count);
        return ResponseEntity.ok(AjaxResponseBody.success(map));
    }

    @NeedToken
    @ApiOperation(value = "测试needToken注解问题", notes = "测试needToken注解问题")
    @PostMapping(value = {"/test/token"})
    public ResponseEntity<?> testToken() {
        AccountInfo loginUser = AccountUtils.getLoginUser();
        System.out.println(loginUser);
        return ResponseEntity.ok(AjaxResponseBody.success());
    }


}